package ru.hh.team02.chat.server;

import ru.hh.team02.chat.client.Client;
import ru.hh.team02.chat.utils.ThreadPerTaskExecutor;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {
    private static final int PORT = 2004;

    private static final ThreadPerTaskExecutor EXECUTOR = new ThreadPerTaskExecutor();

    /*
     * Listen to the port. On connection create a new Client object,
     * start a new thread and bind it to the Client object.
     */
    public void run() {
        ServerSocket listener = null;
        try {
            listener = new ServerSocket(PORT);
            Services.ADMIN_LOGGER.write("waiting for connection...");
            while (true) {
                try {
                    final Socket connection = listener.accept();
                    EXECUTOR.execute(new Client(connection));
                } catch (IOException e) {
                    Services.ADMIN_LOGGER.write("somebody tried to connect but failed because of " + e.getMessage());
                }
            }
        } catch (IOException e) {
            Services.ADMIN_LOGGER.write("server down because of" + e.getMessage());
        } finally {
            try {
                if (listener != null) {
                    listener.close();
                }
            } catch (IOException e) {
                Services.ADMIN_LOGGER.write("can't close server socket because of" + e.getMessage());
            }
        }
    }
}
